package com.woniuxy.usersecurity.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.usersecurity.entity.Permission;
import com.woniuxy.usersecurity.entity.RolePermission;
import com.woniuxy.usersecurity.entity.User;
import com.woniuxy.usersecurity.entity.UserRole;
import com.woniuxy.usersecurity.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class MyUserDetailsService implements UserDetailsService{
    @Autowired
   UserMapper userMapper;
   @Autowired
   RolePermissionMapper rolePermissionMapper;
   @Autowired
   PermissionMapper permissionMapper;
   @Autowired
   UserRoleMapper userRoleMapper;
   @Autowired
   RoleMapper roleMapper;

    //根据前端提交的数据查询出用户的所有
    @Override
    public UserDetails loadUserByUsername
        //前端提供,获取对应用户
        (String username) throws UsernameNotFoundException {
        //此处应根据实际登录来判断
        User user=userMapper.selectById(username);     //获取对应权限
        //查询中间表Role，获取user对应角色
        QueryWrapper<UserRole> queryWrapperRole=new QueryWrapper<>();
        queryWrapperRole.eq("USER_ID",user.getUserId());
        List<UserRole> userRoles= userRoleMapper.selectList(queryWrapperRole);
        //存储权限
        List<Permission> list =new ArrayList<>();
        //查询相关角色相关权限信息
        for (UserRole userRole : userRoles) {
            //根据获取的角色ID去关系表查询相关权限
            QueryWrapper<RolePermission> queryWrapperPermission=new QueryWrapper<>();
            queryWrapperPermission.eq("ROLE_ID",userRole.getRoleId());
            List<RolePermission> permissions= rolePermissionMapper.selectList(queryWrapperPermission);
            //根据获取的权限ID获取具体权限
            //数据库设计时需要加ROLE_
            for (RolePermission permission :permissions ) {
                Permission permission1=permissionMapper.selectById(permission.getPermissionId());
                //list.add(new SimpleGrantedAuthority(permission1.getPermissionName()));
                list.add(permission1);
            }
        }
        user.setPermissions(list);
        //将对象和权限封装
//        org.springframework.security.core.userdetails.User userSecurity= new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
//        System.out.println("userSecurity："+userSecurity.getAuthorities());
        return user;
    }
}
